package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.AppManager;
import com.isunland.managesystem.common.RequestManager;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.receiver.AlarmReceiver;
import com.isunland.managesystem.service.LocationService;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.utils.UpdateUtil;
import com.isunland.managesystem.widget.RoundImageView;
import java.util.HashMap;
import org.json.JSONException;

//import com.umeng.update.UmengUpdateAgent;
//import com.umeng.update.UmengUpdateListener;
//import com.umeng.update.UpdateResponse;
//import com.umeng.update.UpdateStatus;

@SuppressWarnings("deprecation") public class SettingFragment extends Fragment
    implements OnClickListener {
  private static final String TAG = "SettingFragment";
  //private static final int notificationID = 1;
  private static final int REQUEST_CHANGE_ACCOUT = 1;
  private static final int REQUEST_CHANGE_PATH = 2;
  //private static final int REQUEST_SHOW_UPDATE = 3;
  private static final int REQUEST_PERSONNAL_INFO = 4;
  private final String OLD = "OLD";
  private final String NEW = "NEW";
  private final String CHECK = "CHECK";
  private RoundImageView ivUserPhotoSettingFragment;// 登录人头像
  //    private VersionUpdate mVersion;
  //    private long mTotalByte;
  //    private File mAPKFile;
  //    private NotificationManager mNotificationManager;
  //    private Notification mNotification;
  private CheckBox cb_SignoutSide_settingFragment;
  private CurrentUser mUser;
  private SingleFragmentActivity mActivity;
  private String filePath = "";
  //private VersionUpdate mVersion;
  //private long mTotalByte;
  //private NotificationManager mNotificationManager;
  //private File mAPKFile;
  //private Notification mNotification;
  private TextInputEditText et_oldPassword;
  private TextInputEditText et_checkNewPassword;
  private TextInputEditText et_newPassword;
  private AlertDialog mEditDialog;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_setting, container, false);
    findViews(v);
    return v;
  }

  @SuppressWarnings("ConstantConditions") @Override
  public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mActivity = (SingleFragmentActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      if (NavUtils.getParentActivityName(mActivity) != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
      }
      actionBar.setTitle(R.string.set);
    }

    mUser = CurrentUser.newInstance(getActivity());
    getActivity().getApplicationContext();
    super.onCreate(savedInstanceState);
  }

  private void findViews(View v) {

    //View view = v.findViewById(R.id.sv_setting);
    //MyUtils.setPaddingBottomAbove19(view);
    LinearLayout llPersonalInfoSettingFragment =
        (LinearLayout) v.findViewById(R.id.ll_personalInfo_settingFragment);
    ivUserPhotoSettingFragment = (RoundImageView) v.findViewById(R.id.iv_userPhoto_settingFragment);
    TextView tvUserNameSettingFragment =
        (TextView) v.findViewById(R.id.tv_userName_settingFragment);
    TextView tvMemberNameSettingFragment =
        (TextView) v.findViewById(R.id.tv_memberName_settingFragment);
    TextView tvResettingSettingFragment =
        (TextView) v.findViewById(R.id.tv_resetting_settingFragment);
    TextView tvSetNetworkSettingFragment =
        (TextView) v.findViewById(R.id.tv_SetNetwork_settingFragment);
    //修改密码
    TextView tvEditPasswordSettingFragment =
        (TextView) v.findViewById(R.id.tv_editPassword_settingFragment);
    TextView tvUpdateVersionSettingFragment =
        (TextView) v.findViewById(R.id.tv_updateVersion_settingFragment);
    TextView tvProblemSettingFragment = (TextView) v.findViewById(R.id.tv_problem_settingFragment);

    TextView tvAboutUsSettingFragment = (TextView) v.findViewById(R.id.tv_aboutUs_settingFragment);
    Button btnExitSettingFragment = (Button) v.findViewById(R.id.btn_exit_settingFragment);
    cb_SignoutSide_settingFragment = (CheckBox) v.findViewById(R.id.cb_SignoutSide_settingFragment);
    TextView tvShareToFriendSettingFragment =
        (TextView) v.findViewById(R.id.tv_shareToFriend_settingFragment);
    TextView tvFileMange = (TextView) v.findViewById(R.id.tv_fileManage);
    TextView tvUserGuide = (TextView) v.findViewById(R.id.tv_userGuide);
    boolean isOn = isServiceAlarmOn(getActivity().getApplicationContext());

    TextView mtvChangeBindSettingFragment =
        (TextView) v.findViewById(R.id.tv_changeBind_settingFragment);
    //if (BuildConfig.FLAVOR.equals(MyConst.FLAVOR_WEIJIA)){
    //    //tvProblemSettingFragment.setVisibility(View.GONE);
    //    //tvShareToFriendSettingFragment.setVisibility(View.GONE);
    //    //tvUpdateVersionSettingFragment.setVisibility(View.GONE);
    //    tvAboutUsSettingFragment.setVisibility(View.GONE);
    //
    //}
    mtvChangeBindSettingFragment.setOnClickListener(this);
    // isOn=MyUtils.isServiceRunning(getActivity(),
    // "com.isunland.managesystem.service.BDLocationService");
    LogUtil.i(TAG, "isON=" + isOn);

    // filePath=mUser.getPicture();//头像路径
    // fileName=FileUtil.getFileNameByFilePath(filePath);//根据文件路径获取文件名
    // new FileNetWorkUtil(getActivity()).downLoadFile(filePath,
    // fileName,null);
    // mPath=FileUtil.getFileDir()+"/"+fileName;
    // Bitmap bm=BitmapFactory.decodeFile(mPath);
    // ivUserPhotoSettingFragment.setImageBitmap(bm);
    // LogUtil.i("filePath="+filePath);
    // LogUtil.i("fileName="+fileName);
    // LogUtil.i("mPath="+mPath);

    filePath = mUser.getPicture();// 头像路径

    // mUrlImage=ApiConst.getDownLoadUrlByGet(filePath);//get下载路径.
    if (!TextUtils.isEmpty(filePath)) {
      LogUtil.i("filepath=" + filePath);
      // filePath=FileUtil.getThumbNailFilePath(filePath);//缩略图路径
      LogUtil.i("filepathSmall=" + filePath);
      setImageBypath(filePath);
    }

    //
    // ImageLoader imageLoader = RequestManager.getImageLoader();
    //
    // ImageListener listener =
    // ImageLoader.getImageListener(ivUserPhotoSettingFragment,
    // R.drawable.photo, R.drawable.photo);
    // LogUtil.i(mUrlImage );
    // imageLoader.get(mUrlImage, listener);

    tvUserNameSettingFragment.setText(mUser.getRealName());
    tvMemberNameSettingFragment.setText(mUser.getMemberName());

    cb_SignoutSide_settingFragment.setChecked(isOn);
    RelativeLayout rl_SignoutSide_settingFragment =
        (RelativeLayout) v.findViewById(R.id.rl_SignoutSide_settingFragment);
    llPersonalInfoSettingFragment.setOnClickListener(this);
    rl_SignoutSide_settingFragment.setOnClickListener(this);
    tvResettingSettingFragment.setOnClickListener(this);
    tvSetNetworkSettingFragment.setOnClickListener(this);
    tvEditPasswordSettingFragment.setOnClickListener(this);
    tvUpdateVersionSettingFragment.setOnClickListener(this);
    tvProblemSettingFragment.setOnClickListener(this);
    tvAboutUsSettingFragment.setOnClickListener(this);
    btnExitSettingFragment.setOnClickListener(this);
    tvShareToFriendSettingFragment.setOnClickListener(this);
    tvUserGuide.setOnClickListener(this);
    tvFileMange.setOnClickListener(this);
    cb_SignoutSide_settingFragment.setOnCheckedChangeListener(new OnCheckedChangeListener() {

      @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
        LogUtil.i(TAG, "turn=" + arg1);

        if (arg1) {
          Toast.makeText(getActivity(), R.string.hint_start_location_service, Toast.LENGTH_SHORT)
              .show();
        } else {
          Toast.makeText(getActivity(), R.string.hint_stop_location_service, Toast.LENGTH_SHORT)
              .show();
        }
        setServiceAlarm(getActivity(), arg1);
      }
    });
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      // 点击跳转到个人资料界面
      case R.id.ll_personalInfo_settingFragment:

        Intent intent2 = new Intent(getActivity(), PersonalInfoActivity.class);
        intent2.putExtra(PersonalInfoFragment.EXTRA_PATH, filePath);
        startActivityForResult(intent2, REQUEST_PERSONNAL_INFO);
        break;
      //退出登陆
      case R.id.btn_exit_settingFragment:
        AlarmReceiver.stopServiceAlarm(getActivity());
        AppManager.getAppManager().finishAllActivity();
        //退出登陆时不清空用户名和密码,下次显示登陆页面回填用户名和密码.
        mUser.setLogin(false);
        startActivity(new Intent(getActivity(), LoginActivity.class));
        // getActivity().finish();
        break;
      // 点击关于跳转页面
      case R.id.tv_aboutUs_settingFragment:

        // Uri uri = Uri.parse(ApiConst.sDefualtHost);
        // Intent it = new Intent(Intent.ACTION_VIEW, uri);
        // startActivity(it);
        Intent it = new Intent(getActivity(), AboutUsActivity.class);
        startActivity(it);

        break;
      case R.id.tv_SetNetwork_settingFragment:
        showDialog(REQUEST_CHANGE_PATH);
        break;
      case R.id.tv_resetting_settingFragment:
        showDialog(REQUEST_CHANGE_ACCOUT);

        break;
      case R.id.tv_updateVersion_settingFragment:
        //UmengUpdateAgent.forceUpdate(getActivity());
        //UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
        //	@Override
        //	public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
        //		switch (updateStatus) {
        //
        //		case UpdateStatus.No: // has no update
        //
        //			ToastUtil.show(R.string.latest_version);
        //			break;
        //
        //		}
        //	}
        //});
        //volleyPostCheckUpdate();
        UpdateUtil.update(this, true);
        break;
      case R.id.rl_SignoutSide_settingFragment:
        boolean isChecked = cb_SignoutSide_settingFragment.isChecked();
        cb_SignoutSide_settingFragment.setChecked(!isChecked);
        break;
      case R.id.tv_shareToFriend_settingFragment:
        startActivity(new Intent(getActivity(), ShareToFriendsActivity.class));
        break;
      // 意见反馈
      case R.id.tv_problem_settingFragment:
        //                startActivity(new Intent(getActivity(), ProblemBackActivity.class));
        startActivity(new Intent(getActivity(), ProblemBackListActivity.class));
        break;
      // 换绑手机
      case R.id.tv_changeBind_settingFragment:
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.restart_title);
        dialog.setMessage(R.string.ifChangeBind);
        dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            volleyPostChangeSave();
          }
        });

        dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
        dialog.create().show();
        break;
      //修改密码
      case R.id.tv_editPassword_settingFragment:
        changePassword();
        break;
      case R.id.tv_userGuide:
        BaseVolleyActivity.newInstance(this, UserGuidePagerActivity.class, null, 0);
        break;
      //修改密码
      case R.id.tv_fileManage:
        BaseVolleyActivity.newInstance(this, FileManageListActivity.class, null, 0);
        break;
      default:
        break;
    }
  }

  /**
   * 修改密码
   */
  private void changePassword() {
    @SuppressLint("InflateParams") View view =
        getActivity().getLayoutInflater().inflate(R.layout.dialog_edit_password, null);
    TextInputLayout til_oldPassword = (TextInputLayout) view.findViewById(R.id.til_oldPassword);
    et_oldPassword = (TextInputEditText) view.findViewById(R.id.et_oldPassword);
    TextInputLayout til_newPassword = (TextInputLayout) view.findViewById(R.id.til_newPassword);
    et_newPassword = (TextInputEditText) view.findViewById(R.id.et_newPassword);
    TextInputLayout til_checkNewPassword =
        (TextInputLayout) view.findViewById(R.id.til_checkNewPassword);
    et_checkNewPassword = (TextInputEditText) view.findViewById(R.id.et_checkNewPassword);
    til_oldPassword.setHint("验证原密码");
    et_oldPassword.addTextChangedListener(new MyTextWatcher(OLD));
    til_newPassword.setHint("输入新密码");
    et_newPassword.addTextChangedListener(new MyTextWatcher(NEW));
    til_checkNewPassword.setHint("验证新密码");
    et_checkNewPassword.addTextChangedListener(new MyTextWatcher(CHECK));

    mEditDialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.edit_password)
        .setView(view)
        .setPositiveButton(R.string.confirm, null)
        .setNegativeButton(R.string.cancel, null)
        .create();

    mEditDialog.setOnShowListener(new DialogInterface.OnShowListener() {
      @Override public void onShow(DialogInterface dialogInterface) {
        Button sureBtn = mEditDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        sureBtn.setOnClickListener(new OnClickListener() {
          @Override public void onClick(View view) {
            if (!TextUtils.isEmpty(et_oldPassword.getText().toString()) && !TextUtils.isEmpty(
                et_newPassword.getText().toString()) && !TextUtils.isEmpty(
                et_checkNewPassword.getText().toString())) {
              if ((et_newPassword.length() <= 10 && et_newPassword.length() >= 6) && (
                  et_checkNewPassword.length() <= 10
                      && et_checkNewPassword.length() >= 6)) {
                volleyPostNewPassward();
              } else {
                ToastUtil.show(R.string.complete_hint);
              }
            } else {
              ToastUtil.show(R.string.complete_hint);
            }
          }
        });
      }
    });
    mEditDialog.show();
  }

  private void volleyPostNewPassward() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.MODIFY_PASSWORD);
    HashMap<String, String> params = new HashMap<>();
    params.put("account", mUser.getName());//登录账号
    params.put("oldPas", et_oldPassword.getText().toString());
    params.put("newPas", et_newPassword.getText().toString());
    params.put("cofPas", et_checkNewPassword.getText().toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage successMessage = new Gson().fromJson(arg0, SuccessMessage.class);
        String result = successMessage.getResult();
        String message = successMessage.getMessage();

        if ("1".equalsIgnoreCase(result)) {
          //修改成功后到登录界面
          ToastUtil.show(R.string.restart_login);
          mEditDialog.dismiss();
          //登录密码置空
          mUser.setPassword("");

          Intent i = new Intent(getActivity(), LoginActivity.class);
          startActivity(i);
          getActivity().finish();
        } else {
          ToastUtil.show(message);
        }
      }
    });
  }

  /**
   * 换绑手机
   */
  protected void volleyPostChangeSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CHANGE_BIND);
    HashMap<String, String> params = new HashMap<>();

    final String id = MyUtils.getDeviceId(getActivity());
    if (TextUtils.isEmpty(id)) {

      return;
    }

    params.put("type", "mobile");
    params.put("phoneIdentifyNumber", id);
    params.put("jobNo", mUser.getJobNumber());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
        String ifSuccess = message.getResult();
        String ifSuccessMessage = message.getMessage();
        ToastUtil.show(ifSuccessMessage);
        if ("1".equalsIgnoreCase(ifSuccess)) {
          mUser.setPhoneIdentifyNumber(id);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.changeFail);
        LogUtil.e("VolleyError" + arg0);
      }
    });
  }

  private void showDialog(int type) {
    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (type) {
      case REQUEST_CHANGE_PATH:
        dialog = new NetWorkSettingDialogFragment();
        break;
      //case REQUEST_SHOW_UPDATE:
      //    String hint = getResources().getString(R.string.updateHint, mVersion.getWhatsNew());
      //    dialog = BaseConfirmDialogFragment.newInstance(hint, R.string.checkForUpdate);
      //    break;
      case REQUEST_CHANGE_ACCOUT:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.changeAccountConfirm);

        break;
      default:
        return;
    }

    // CustomerDialogFragment dialog = CustomerDialogFragment
    // .newInstance(type);
    dialog.setTargetFragment(SettingFragment.this, type);
    dialog.show(fm, "");
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        return true;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  //private void volleyPostCheckUpdate() {
  //    MyUtils.showDialogLoading(getActivity());
  //    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LATEST_VERSION);
  //    HashMap<String, String> params = new HashMap<>();
  //    mActivity.volleyPost(url, params, new VolleyResponse() {
  //
  //        @Override
  //        public void onVolleyResponse(String arg0) throws JSONException {
  //
  //            handleResponseUpdate(arg0);
  //        }
  //
  //        @Override
  //        public void onVolleyError(VolleyError arg0) {
  //            // Auto-generated method stub
  //
  //        }
  //    });
  //
  //}

  //private void handleResponseUpdate(String jsonString) {
  //    try {
  //        LogUtil.i(TAG, "response=" + jsonString);
  //        mVersion = new Gson().fromJson(jsonString, VersionUpdate.class);
  //        if (mVersion == null) {
  //            return;
  //        }
  //        int currentVersion = MyUtils.getVersionCode(getActivity());
  //
  //        if (mVersion.getVerCode() <= currentVersion) {
  //            Toast.makeText(getActivity(), R.string.latest_version, Toast.LENGTH_SHORT).show();
  //            return;
  //
  //        }
  //
  //        mTotalByte = mVersion.getTotalByte();
  //        showDialog(REQUEST_SHOW_UPDATE);
  //    } catch (Exception e) {
  //        e.printStackTrace();
  //
  //        LogUtil.e(TAG, "e=" + e.toString(), e);
  //
  //    }
  //}

  //    private void downloadAPK() {
  //
  //        RequestParams params2 = new RequestParams("id", mVersion.getId());
  //
  //        mAPKFile = new File(FileUtil.getFileDir(), mVersion.getApkName() + ".apk");
  //
  //        //noinspection ResultOfMethodCallIgnored
  //        mAPKFile.getParentFile().mkdirs();
  //        DefaultAsyncHttpClient.post(ApiConst.URL_DOWNLOAD_APK, params2, new FileAsyncHttpResponseHandler(mAPKFile) {
  //
  //            @Override
  //            public void onStart() {
  //                ToastUtil.show(R.string.isDownLoading);
  //                //Toast.makeText(getActivity(), , Toast.LENGTH_SHORT).show();
  ////				boolean checkReadPermission=mActivity.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
  ////				if(!checkReadPermission){
  ////					return;
  ////				}
  //                initNotifycation();
  //            }
  //
  //            @Override
  //            public void onProgress(long bytesWritten, long totalSize) {
  //
  //                notifyProgress(bytesWritten, mTotalByte);
  //
  //            }
  //
  //
  //            @Override
  //            public void onSuccess(int statusCode, Header[] headers, File response) {
  //
  //                Intent intent = getInstallIntent(mAPKFile);
  //                notifyInstallAPK(intent);
  //                if (isAdded()) {
  //                    // 用户离开当前界面,fragment在detach状态下.startActivity()会报错.
  //                    startActivity(intent);
  //                }
  //
  //            }
  //
  //            @Override
  //            public void onFailure(int arg0, Header[] arg1, Throwable arg2, File arg3) {
  //                MyUtils.dismissDialog();
  //                ToastUtil.show(R.string.download_failed);
  //                //Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_SHORT).show();
  //                LogUtil.i(TAG, "responseError=" + arg0 + arg2 + arg3);
  //            }
  //        });
  //    }

  //private void notifyInstallAPK(Intent intent) {
  //
  //    PendingIntent pi = PendingIntent.getActivity(MyApplication.getAppContext(), 0, intent, 0);
  //    RemoteViews remoteViews = new RemoteViews(MyApplication.getAppContext().getPackageName(), R.layout.down_notification);
  //    remoteViews.setImageViewResource(R.id.IconIV, R.drawable.ic_launcher);
  //    remoteViews.setTextViewText(R.id.progressTv, "下载完成");
  //    remoteViews.setProgressBar(R.id.progressBar, 100, 100, false);
  //    mNotification.contentView = remoteViews;
  //
  //    mNotification.contentIntent = pi;
  //    mNotification.flags = Notification.FLAG_AUTO_CANCEL;
  //    mNotificationManager.notify(notificationID, mNotification);
  //    // notificationManager.cancel(notificationID);
  //}

  //private Intent getInstallIntent(File response) {
  //    Intent intent = new Intent(Intent.ACTION_VIEW);
  //
  //    intent.setDataAndType(Uri.fromFile(response), "application/vnd.android.package-archive");
  //    return intent;
  //}

  //private void initNotifycation() {
  //    PendingIntent pi = PendingIntent.getActivity(getActivity(), 0,
  //            new Intent(getActivity(), SettingActivity.class), 0);
  //    mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
  //    mNotification = new Notification();
  //    mNotification.icon = R.drawable.ic_launcher;// 设置通知消息的图标
  //    mNotification.tickerText = "正在下载。。。";// 设置通知消息的标题
  //    mNotification.contentIntent = pi;
  //
  //}

  //private void notifyProgress(long bytesWritten, long totalSize) {
  //    int progressPercentage = (int) ((bytesWritten * 100 / totalSize));
  //
  //    DecimalFormat format = new DecimalFormat("0.00");
  //    String progress = format.format(progressPercentage);
  //    RemoteViews remoteViews = new RemoteViews(MyApplication.getAppContext().getPackageName(), R.layout.down_notification);
  //    remoteViews.setImageViewResource(R.id.IconIV, R.drawable.ic_launcher);
  //    remoteViews.setTextViewText(R.id.progressTv, "已下载" + progress + "%");
  //
  //    remoteViews.setProgressBar(R.id.progressBar, 100, progressPercentage, false);
  //    mNotification.contentView = remoteViews;
  //    mNotificationManager.notify(notificationID, mNotification);
  //}

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_CHANGE_ACCOUT) {
      AlarmReceiver.stopServiceAlarm(getActivity());
      mUser.clear();
      AppManager.getAppManager().finishAllActivity();
      startActivity(new Intent(getActivity(), LoginActivity.class));
      Toast.makeText(getActivity(), R.string.loginLoseEficacy, Toast.LENGTH_SHORT).show();
    }
    if (requestCode == REQUEST_CHANGE_PATH) {
      AlarmReceiver.stopServiceAlarm(getActivity());
      // mUser.update("", "", "", "", "", "");
      AppManager.getAppManager().finishAllActivity();
      Intent intent = new Intent(getActivity(), LoginActivity.class);

      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
      // getActivity().finish();

      Toast.makeText(getActivity(), R.string.loginLoseEficacy, Toast.LENGTH_SHORT).show();
    }
    //        if (requestCode == REQUEST_SHOW_UPDATE) {
    ////			boolean checkWritePermission=mActivity.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    ////			if(!checkWritePermission){
    ////				return;
    ////			}
    //            downloadAPK();
    //        }
    if (requestCode == REQUEST_PERSONNAL_INFO) {
      String path = data.getStringExtra("result");
      // setImageBypath(path);
      filePath = mUser.getPicture();// 头像路径
      // if (!TextUtils.isEmpty(filePath)) {
      // filePath=FileUtil.getThumbNailFilePath(filePath);//获取缩略图路径
      // LogUtil.i("headImage="+mUser.getPicture());
      // }
      ivUserPhotoSettingFragment.setImageBitmap(BitmapFactory.decodeFile(path, null));
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  // 登录人头像显示
  public void setImageBypath(String filePath) {
    String urlImage = ApiConst.getDownLoadUrlByGet(filePath);
    LogUtil.i("urlImage=" + urlImage);
    ImageLoader imageLoader = RequestManager.getImageLoader();

    ImageListener listener =
        ImageLoader.getImageListener(ivUserPhotoSettingFragment, R.drawable.photo,
            R.drawable.photo);

    imageLoader.get(urlImage, listener);
  }

  public void setServiceAlarm(Context context, boolean isOn) {
    Intent alarmIntent = new Intent(context, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    LogUtil.i(TAG, "alarm=" + isOn);
    if (isOn) {

      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60, pi);
    } else {
      alarmManager.cancel(pi);
      pi.cancel();
      getActivity().stopService(new Intent(getActivity(), LocationService.class));
    }

    //PreferenceManager.getDefaultSharedPreferences(context).edit()
    //        .putBoolean("isAlarmOn", isOn).commit();
  }

  public boolean isServiceAlarmOn(Context context) {
    Intent i = new Intent(context, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_NO_CREATE);
    return pi != null;
  }

  private class MyTextWatcher implements TextWatcher {

    private String type = "";

    MyTextWatcher(String type) {
      this.type = type;
    }

    @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

      if (OLD.equals(type)) {
        if (charSequence.length() == 0 || TextUtils.isEmpty(charSequence)) {
          et_oldPassword.setError("该输入项为必输项");
        }
      } else if (NEW.equals(type)) {
        if (charSequence.length() < 6 || charSequence.length() > 10) {
          et_newPassword.setError("输入内容长度必须介于6和10之间");
        }
        if (charSequence.length() == 0 || TextUtils.isEmpty(charSequence)) {
          et_newPassword.setError("该输入项为必输项");
        }
      } else if (CHECK.equals(type)) {
        if (charSequence.length() < 6 || charSequence.length() > 10) {
          et_checkNewPassword.setError("输入内容长度必须介于6和10之间");
        }
        if (charSequence.length() == 0 || TextUtils.isEmpty(charSequence)) {
          et_checkNewPassword.setError("该输入项为必输项");
        }
      }
    }

    @Override public void afterTextChanged(Editable editable) {
    }
  }
}
